﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
//using System.Runtime.InteropServices; //调用WINDOWS API函数时要用到 
using Microsoft.Win32;


namespace myking
{
    public partial class Form1 : Form
    {
        #region API函数申明
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hwnd, int wMsg, string wParam, string lParam);

        //读取进程内存的函数
        [DllImport("kernel32.dll ")]
        static extern bool ReadProcessMemory(int hProcess, int lpBaseAddress, out int lpBuffer, int nSize, out int lpNumberOfBytesRead);

        //通过GetWindowThreadProcessId读取查找窗体句柄进程的PID值
        [DllImport("user32.dll")]
        private static extern int GetWindowThreadProcessId(IntPtr id, out int pid);

        //得到目标进程句柄的函数
        [DllImport("kernel32.dll")]
        public static extern int OpenProcess(uint dwDesiredAccess, bool bInheritHandle, int dwProcessId);

        [DllImport("user32")]
        public extern static int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll ", EntryPoint = "GetDlgItem")]
        public static extern IntPtr GetDlgItem(IntPtr hParent, int nIDParentItem);

        //[DllImport("user32.dll", EntryPoint = "SendMessage")]
        //public static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, System.Text.StringBuilder lParam);

        [DllImport("user32.dll", EntryPoint="SendMessageA")]
        private static extern int SendMessage (IntPtr hwnd, int wMsg, int wParam, StringBuilder lParam);

        [DllImport("user32.dll", CharSet = CharSet.Ansi)]
        public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);


        const int PROCESS_ALL_ACCESS = 0x1F0FFF;
        const int PROCESS_VM_READ = 0x0010;
        const int PROCESS_VM_WRITE = 0x0020;

        #region sendinput的api相关定义
        [DllImport("user32.dll")]
        public static extern UInt32 SendInput(UInt32 nInputs, Input[] pInputs, int cbSize);

        [StructLayout(LayoutKind.Sequential)]
        public struct MouseInput
        {
            public Int32 dx;
            public Int32 dy;
            public Int32 Mousedata;
            public Int32 dwFlag;
            public Int32 time;
            public IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct tagKEYBDINPUT
        {
            Int16 wVk;
            Int16 wScan;
            Int32 dwFlags;
            Int32 time;
            IntPtr dwExtraInfo;
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct tagHARDWAREINPUT
        {
            Int32 uMsg;
            Int16 wParamL;
            Int16 wParamH;
        }

        [StructLayout(LayoutKind.Explicit)]
        public struct Input
        {
            [FieldOffset(0)]  public Int32 type;
            [FieldOffset(4)]  public MouseInput mi;
            [FieldOffset(4)]  public tagKEYBDINPUT ki;
            [FieldOffset(4)]  public tagHARDWAREINPUT hi;
        }

        const int MouseEvent_Absolute = 0x8000;
        const int MouserEvent_Hwheel = 0x01000;
        const int MouseEvent_Move = 0x0001;
        const int MouseEvent_Move_noCoalesce = 0x2000;
        const int MouseEvent_LeftDown = 0x0002;
        const int MouseEvent_LeftUp = 0x0004;
        const int MouseEvent_MiddleDown = 0x0020;
        const int MouseEvent_MiddleUp = 0x0040;
        const int MouseEvent_RightDown = 0x0008;
        const int MouseEvent_RightUp = 0x0010;
        const int MouseEvent_Wheel = 0x0800;
        const int MousseEvent_XUp = 0x0100;
        const int MousseEvent_XDown = 0x0080;

        #endregion

        #endregion

        #region 定义变量

        /// <summary>
        /// 运行模式 0 直接启动 ,1 查询启动
        /// </summary>
        private string runmode { get; set; }

        #endregion


        ProcessStartInfo psInfo = new ProcessStartInfo();
        Process pro = new Process();

        /// <summary>
        /// 需要启动的程序
        /// </summary>
        public string filename { get; set; }

        public static string scriptpathname { get; set; }

        private static IntPtr parent_handle { get; set; }

        KeyboardHook k_hook;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string userid = scriptpathname = Properties.Settings.Default.userid;
            string script = scriptpathname = Properties.Settings.Default.scriptpath;

            label1.Text = script;
            txtuserid.Text = userid;

            psInfo = new ProcessStartInfo(getPath());

            psInfo.RedirectStandardOutput = true;
            psInfo.RedirectStandardError = true;
            psInfo.UseShellExecute = false;
            pro.StartInfo = psInfo;

            #region 安装键盘钩子

            k_hook = new KeyboardHook();
            k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下 
            k_hook.Start();//安装键盘钩子
            parent_handle = this.Handle;

            #endregion


        }


        private void hook_KeyDown(object sender, KeyEventArgs e) 
        { 
            //判断按下的键（Alt + A） 
            //if (e.KeyValue == (int)Keys.A && (int)Control.ModifierKeys == (int)Keys.Alt) 
            if (e.KeyValue == (int)Keys.F12)
            {

                scriptClass.setwindowShow(parent_handle);
                
                //System.Windows.Forms.MessageBox.Show("按下了指定快捷键组合"); 
             } 
        } 

        private  string getPath()
        {
            filename = txtgamepath.Text;

            if (string.IsNullOrEmpty(filename))
            {
                filename = ConfigurationManager.AppSettings["setting:path"];
            }

            if (string.IsNullOrEmpty(filename))
            {
                throw new Exception("未配置需要启动的程序!");
            }
            return filename;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                pro.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ",请检查配置文件的游戏路径是否正确!");
            }
            button1.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;

            button2.Enabled = true;
            button5.Enabled = true;
            button7.Enabled = true;
            button8.Enabled = true;
            checkBoxdm.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                pro.Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ",程序已经关闭或未正启动");
            }

            scriptClass.businesstypeName = "N";
            scriptClass.checkresponflag = "N";

            button1.Enabled = true;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button5.Enabled = false;
            button7.Enabled = false;
            button8.Enabled = false;

            btnstop.Text = "暂停";
            btnstop.Enabled = false;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                scriptpathname = openFileDialog1.FileName;
                button3.Enabled = true;
                button4.Enabled = true;
                label1.Text = scriptpathname;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

            if (checkuser.Checked)
            {
                string settingValue = ConfigurationManager.AppSettings["userid"];
                // 修改设置值
                ConfigurationManager.AppSettings["userid"] = txtuserid.Text;

                // 刷新配置节以使更改生效
                ConfigurationManager.RefreshSection("appSettings");
                settingValue = ConfigurationManager.AppSettings["userid"];
            }

            string debug = Properties.Settings.Default.debug;

            scriptClass.debug = debug;

            if (scriptClass.programhWnd == IntPtr.Zero)
            {
                MessageBox.Show("主窗口未获取到,请检查id 是否正确,游戏是否正常开启!");
                return;
            }

            scriptClass.businesstypeName = "Y";

            scriptClass.titlename = textBox2.Text;

            scriptClass.userid = txtuserid.Text.Trim();
            scriptClass.passwd = txtpasswd.Text.Trim();

            string errmsg = string.Empty;
            ArrayList commandlist = new ArrayList();

           

            if (scriptClass.GetScript(scriptpathname, out errmsg) < 0)
            {
                MessageBox.Show(errmsg);
                return;
            }

            if (cbxautocheck.Checked)
            {
                string id = txtuserid.Text.Trim();

                if (string.IsNullOrEmpty(id))
                {
                    MessageBox.Show("请输入你的游戏id");
                    return;
                }

                IntPtr hWndmsgParent = IntPtr.Zero;
                IntPtr hWndmsg = scriptClass.getmsghandle(out hWndmsgParent, id);
                if (hWndmsg == IntPtr.Zero)
                {
                    MessageBox.Show("请先关闭消息框再重新打开!快捷键CTRL+F3");
                    return;
                }
                //const int WM_SETTEXT = 0xC;
                //SendMessage(hWndmsgParent, WM_SETTEXT, textBox2.Text + "消息", textBox2.Text + "消息");
                scriptClass.checkhWnd = hWndmsg;
                //scriptClass.programhWnd = hWndmsgParent;
            }

            int delay = Convert.ToInt32(txtsec.Text);
            Thread.Sleep(delay);

            if (checkBoxdm.Checked)
            {
                scriptClass.dmtypeFlag = "Y";
            }
            else
            {
                scriptClass.dmtypeFlag = "N";
            }

            if (string.IsNullOrEmpty(textBox2.Text))
            {
                textBox2.Text = "myking" + txtuserid.Text;
            }

            if (checkBoxRe.Checked)
            {
                scriptClass.reconnetFlag = "Y";
            }
            else
            {
                scriptClass.reconnetFlag = "N";
            }

            scriptClass.reconnetTime = Convert.ToInt32(txtreconnettime.Text);

            //this.Text = textBox2.Text;
            Thread f = new Thread(loopsendmessage);
            f.Start();
            button3.Enabled = false;
            button3.Enabled = true;
            cbxautocheck.Enabled = false;
            checkBoxdm.Enabled = false;

            btnstop.Text = "暂停";
            btnstop.Enabled = true;
        }

        private void loopsendmessage()
        {
            scriptClass.MySendMessage();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            scriptClass.businesstypeName = "N";
            button3.Enabled = true;
            cbxautocheck.Enabled = true;
            if (scriptClass.programhWnd != IntPtr.Zero)
            {
                scriptClass.dmDispose();
            }
            btnstop.Text = "暂停";
            btnstop.Enabled = false;
            checkBoxdm.Enabled = true;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (button5.Text == "显示")
            {
                if (scriptClass.programhWnd != IntPtr.Zero)
                { 
                    scriptClass.setwindowShow(scriptClass.programhWnd);
                }
                button5.Text = "隐藏";
            }
            else
            {
                if (scriptClass.programhWnd != IntPtr.Zero)
                {
                    scriptClass.setwindowHide(scriptClass.programhWnd);
                }
                scriptClass.setwindowHide();
                button5.Text = "显示";
            }
            
        }

        private void button8_Click(object sender, EventArgs e)
        {
            scriptClass.titlename = textBox2.Text;
            this.Text = textBox2.Text;
            IntPtr hWnd;
            hWnd = pro.MainWindowHandle; //获取Form1.exe主窗口句柄
            scriptClass.programhWnd = hWnd;
            scriptClass.ChangeTitle();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            scriptClass.businesstypeName = "N";
            scriptClass.checkresponflag = "N";
            e.Cancel = false;
            System.Environment.Exit(0);
        }

        private void txtshowmsg_Click(object sender, EventArgs e)
        {
            if (txtshowmsg.Text == "显示消息框")
            {
                if (scriptClass.msgHwnd != IntPtr.Zero)
                {
                    scriptClass.setwindowShow(scriptClass.msgHwnd);
                }
                txtshowmsg.Text = "隐藏消息框";
            }
            else
            {
                if (scriptClass.msgHwnd != IntPtr.Zero)
                {
                    scriptClass.setwindowHide(scriptClass.msgHwnd);
                }
                txtshowmsg.Text = "显示消息框";
            }
        }

        private void btnstop_Click(object sender, EventArgs e)
        {
            if (btnstop.Text == "暂停")
            {
                scriptClass.stopFlag = "Y";
                btnstop.Text = "继续";
            }
            else
            {
                scriptClass.stopFlag = "N";
                btnstop.Text = "暂停";
            }
        }

        private void checkuser_CheckedChanged(object sender, EventArgs e)
        {
            if (checkuser.Checked)
            {
                txtuserid.PasswordChar = new char();
            }
            else
            {
                txtuserid.PasswordChar = '*';
            }
        }

        private void checkpwd_CheckedChanged(object sender, EventArgs e)
        {
            if (checkpwd.Checked)
            {
                txtpasswd.PasswordChar = new char();
            }
            else
            {
                txtpasswd.PasswordChar = '*';
            }
        }

        private void checkBoxRe_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxRe.Checked)
            {
                scriptClass.reconnetFlag = "Y";
            }
            else
            {
                scriptClass.reconnetFlag = "N";
            }
        }

        private void btnhide_Click(object sender, EventArgs e)
        {
            scriptClass.setwindowHide(parent_handle);
        }

        private void btn_find_Click(object sender, EventArgs e)
        {
            string id = txtuserid.Text.Trim();

            if (string.IsNullOrEmpty(id))
            {
                MessageBox.Show("角色id为空!请输入");
                return;
            }

            IntPtr hWndmsgParent = new IntPtr();

            scriptClass.programhWnd = scriptClass.getMasterhandle(out hWndmsgParent, id);

            if (scriptClass.programhWnd == IntPtr.Zero)
            {
                MessageBox.Show("主窗口未获取到,请检查id 是否正确,游戏是否正常开启!");
                return;
            }
            button3.Enabled = true;
        }

        private void checkBoxdm_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void btnhelp_Click(object sender, EventArgs e)
        {
            FrmHelp stk = new FrmHelp();
            stk.ShowDialog();
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void txtgamepath_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnhtml_Click(object sender, EventArgs e)
        {
            //调用系统默认的浏览器
            System.Diagnostics.Process.Start("https://blog.csdn.net/qqqwwqtie/article/details/134263440");
        }
    }
}
